<template>
  <section class="todoapp">
    <!-- 使用组件 -->
    <todo-header @add="add"></todo-header>
    <!-- 将列表传递给main组件 -->
    <todo-main
      @changeAll="changeAll"
      :todoList="showList"
      @del="del"
      @change="change"
    ></todo-main>
    <!-- 底部组件不是时刻显示的, 显示的前提是有数据 -->
    <todo-footer
      v-if="todoList.length"
      @clear="clear"
      :todoList="todoList"
      @selectTodo="selectTodo"
      :condition="condition"
    ></todo-footer>
  </section>
</template>

<script>
// 导入三个组件
import TodoHeader from './components/TodoHeader'
import TodoMain from './components/TodoMain'
import TodoFooter from './components/TodoFooter'
export default {
  // 挂载组件
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter
  },
  data() {
    return {
      // 本地存储读取数据
      todoList: JSON.parse(localStorage.getItem('todoList')) || [],
      condition: 'all'
    }
  },
  methods: {
    del(id) {
      //   console.log(id)
      //   拿到id找索引截取截取
      const index = this.todoList.findIndex((item) => item.id === id)
      this.todoList.splice(index, 1)
    },
    change(id, status) {
      //   console.log(id)
      //   console.log(status)
      //  拿到id找元素
      const obj = this.todoList.find((item) => item.id === id)
      //  更新状态
      obj.isDone = status
    },
    // 清除已完成
    clear() {
      // 只需要将isDone值是false过滤出来
      this.todoList = this.todoList.filter((item) => !item.isDone)
    },
    // 新增
    add(info) {
      // 新增
      this.todoList.unshift({ id: Date.now(), info, isDone: false })
    },
    changeAll(state) {
      this.todoList.forEach((item) => (item.isDone = state))
    },
    // 将接收到的三个按钮的标识更改condition, 依据更改过来的condition,使用计算属性过滤数组
    selectTodo(str) {
      this.condition = str
    }
  },
  // 将数据存储到本地
  watch: {
    todoList: {
      handler(nVal) {
        localStorage.setItem('todoList', JSON.stringify(nVal))
      },
      deep: true
    }
  },
  computed: {
    showList() {
      if (this.condition === 'active') {
        return this.todoList.filter((item) => !item.isDone)
      } else if (this.condition === 'completed') {
        return this.todoList.filter((item) => item.isDone)
      } else {
        return this.todoList
      }
    }
  }
}
</script>

<style></style>
